<script setup lang="ts">
import type { UploadFile } from "element-plus"
import type * as ApiType from "./api/type"
import { ElMessage } from "element-plus"
import { onMounted, ref, shallowRef } from "vue"

// 引入API
import { getEnterpriseParams, saveEnterpriseParams, uploadFile } from "./api/index"

// 表单数据
const form = ref<ApiType.SaveEnterpriseParamsRequest>({
  enterpriseName: "",
  enterprisePhone: "",
  enterpriseEmail: "",
  wechatLink: "",
  logoUrl: "",
  wechatQrUrl: ""
})

// 状态管理
const loading = ref(true) // 页面加载状态
const submitLoading = ref(false) // 提交按钮加载状态
const formRef = shallowRef<any>(null) // 表单实例
const uploadLoading = ref(false) // 上传加载状态

// 文件上传相关
const logoFileList = ref<UploadFile[]>([])
const wechatFileList = ref<UploadFile[]>([])

// 初始化页面数据
onMounted(async () => {
  try {
    const res = await getEnterpriseParams()
    if (res.code === 200) {
      form.value = res.data
      // 回显已上传文件
      if (form.value.logoUrl) {
        logoFileList.value = [{
          name: "企业LOGO",
          url: form.value.logoUrl,
          uid: Date.now(),
          status: "success"
        }]
      }
      if (form.value.wechatQrUrl) {
        wechatFileList.value = [{
          name: "公众号二维码",
          url: form.value.wechatQrUrl,
          uid: Date.now() + 1,
          status: "success"
        }]
      }
    } else {
      ElMessage.error(res.message || "加载数据失败")
    }
  } catch (error: any) {
    console.error("初始化失败:", error.message)
    ElMessage.error("系统异常，请刷新页面重试")
  } finally {
    loading.value = false
  }
})

// LOGO上传前校验
function beforeLogoUpload(file: File) {
  const isImage = file.type.startsWith("image/")
  const isLt500K = file.size / 1024 < 500

  if (!isImage) {
    ElMessage.error("请上传图片格式文件！")
    return false
  }
  if (!isLt500K) {
    ElMessage.error("文件大小不能超过500KB！")
    return false
  }
  return true
}

// 公众号二维码上传前校验
function beforeQrUpload(file: File) {
  const isImage = file.type.startsWith("image/")
  const isLt1M = file.size / 1024 / 1024 < 1

  if (!isImage) {
    ElMessage.error("请上传图片格式文件！")
    return false
  }
  if (!isLt1M) {
    ElMessage.error("文件大小不能超过1MB！")
    return false
  }
  return true
}

// LOGO自定义上传
async function handleLogoUpload(options: { file: File }) {
  uploadLoading.value = true
  try {
    const formData = new FormData()
    formData.append("file", options.file)
    const res = await uploadFile(formData)

    if (res.code === 200) {
      form.value.logoUrl = res.data.fileUrl
      logoFileList.value = [{
        name: options.file.name,
        url: res.data.fileUrl,
        uid: Date.now(),
        status: "success"
      }]
      ElMessage.success("LOGO上传成功")
    } else {
      ElMessage.error(res.message || "LOGO上传失败")
    }
  } catch (error: any) {
    console.error("LOGO上传异常:", error.message)
    ElMessage.error("上传失败，请重试")
  } finally {
    uploadLoading.value = false
  }
}

// 公众号二维码自定义上传
async function handleQrUpload(options: { file: File }) {
  uploadLoading.value = true
  try {
    const formData = new FormData()
    formData.append("file", options.file)
    const res = await uploadFile(formData)

    if (res.code === 200) {
      form.value.wechatQrUrl = res.data.fileUrl
      wechatFileList.value = [{
        name: options.file.name,
        url: res.data.fileUrl,
        uid: Date.now() + 1,
        status: "success"
      }]
      ElMessage.success("二维码上传成功")
    } else {
      ElMessage.error(res.message || "二维码上传失败")
    }
  } catch (error: any) {
    console.error("二维码上传异常:", error.message)
    ElMessage.error("上传失败，请重试")
  } finally {
    uploadLoading.value = false
  }
}

// 移除LOGO（无弹窗确认）
function handleLogoRemove() {
  form.value.logoUrl = ""
  logoFileList.value = []
  ElMessage.success("已移除LOGO")
}

// 移除公众号二维码（无弹窗确认）
function handleQrRemove() {
  form.value.wechatQrUrl = ""
  wechatFileList.value = []
  ElMessage.success("已移除二维码")
}

// 表单提交
async function handleSubmit() {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
  } catch (error: any) {
    console.error("表单校验失败:", error.message)
    return
  }

  submitLoading.value = true
  try {
    const res = await saveEnterpriseParams(form.value)
    if (res.code === 200) {
      ElMessage.success("保存成功！")
    } else {
      ElMessage.error(res.message || "保存失败，请重试")
    }
  } catch (error: any) {
    console.error("提交失败:", error.message)
    ElMessage.error("系统异常，保存失败")
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
function handleReset() {
  formRef.value?.resetFields()
  // 重置文件列表
  logoFileList.value = form.value.logoUrl
    ? [{
        name: "企业LOGO",
        url: form.value.logoUrl,
        uid: Date.now(),
        status: "success"
      }]
    : []
  wechatFileList.value = form.value.wechatQrUrl
    ? [{
        name: "公众号二维码",
        url: form.value.wechatQrUrl,
        uid: Date.now() + 1,
        status: "success"
      }]
    : []
  ElMessage.success("表单已重置")
}
</script>

<template>
  <div class="enterprise-params-page">
    <!-- 标题区域（带边框，独占一行） -->
    <div class="page-header">
      <div class="header-content">
        <h2>企业参数设置</h2>
        <p class="sub-title">
          配置企业基础信息及展示参数
        </p>
      </div>
    </div>

    <!-- 表单区域（带边框，独占一行） -->
    <div class="form-container">
      <!-- 加载状态 -->
      <el-skeleton
        v-if="loading"
        :loading="loading"
        :rows="8"
        style="width: 100%; padding: 20px 0;"
        :animated="true"
      />

      <!-- 表单内容 -->
      <el-form
        ref="formRef"
        :model="form"
        label-width="140px"
        size="default"
        class="params-form"
        v-else
      >
        <!-- 企业名称 -->
        <el-form-item
          label="企业名称"
          prop="enterpriseName"
          :rules="[{ required: true, message: '请输入企业名称', trigger: 'blur' }]"
        >
          <el-input
            v-model="form.enterpriseName"
            placeholder="请输入企业全称"
            max-length="50"
            clearable
          />
        </el-form-item>

        <!-- 企业电话 -->
        <el-form-item
          label="企业电话"
          prop="enterprisePhone"
          :rules="[{ required: true, message: '请输入企业电话', trigger: 'blur' }]"
        >
          <el-input
            v-model="form.enterprisePhone"
            placeholder="请输入联系电话"
            max-length="20"
            clearable
          />
        </el-form-item>

        <!-- 企业邮箱 -->
        <el-form-item
          label="企业邮箱"
          prop="enterpriseEmail"
          :rules="[
            { required: true, message: '请输入企业邮箱', trigger: 'blur' },
            { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
          ]"
        >
          <el-input
            v-model="form.enterpriseEmail"
            placeholder="请输入企业官方邮箱"
            max-length="50"
            clearable
          />
        </el-form-item>

        <!-- 企业LOGO上传 -->
        <el-form-item label="企业LOGO">
          <div class="upload-group">
            <el-upload
              class="logo-upload"
              :file-list="logoFileList"
              :before-upload="beforeLogoUpload"
              :http-request="handleLogoUpload"
              :on-remove="handleLogoRemove"
              accept=".jpg,.jpeg,.png"
              :disabled="uploadLoading"
            >
              <el-button type="primary" :loading="uploadLoading">
                选择图片
              </el-button>
            </el-upload>

            <div class="preview-img-group">
              <el-image
                v-for="(file, index) in logoFileList"
                :key="index"
                :src="file.url"
                class="preview-img"
                fit="cover"
              />
            </div>
          </div>
          <template #tip>
            <div class="upload-tip">
              支持JPG/PNG格式，文件大小不超过500KB，建议尺寸50×50px
            </div>
          </template>
        </el-form-item>

        <!-- 微信公众号链接 -->
        <el-form-item
          label="公众号关注链接"
          prop="wechatLink"
        >
          <el-input
            v-model="form.wechatLink"
            placeholder="请输入公众号跳转链接"
            max-length="200"
            clearable
          />
          <template #help>
            <div class="form-help">
              用户扫码后跳转的公众号关注页面链接
            </div>
          </template>
        </el-form-item>

        <!-- 微信公众号二维码 -->
        <el-form-item label="公众号二维码">
          <div class="upload-group">
            <el-upload
              class="qr-upload"
              :file-list="wechatFileList"
              :before-upload="beforeQrUpload"
              :http-request="handleQrUpload"
              :on-remove="handleQrRemove"
              accept=".jpg,.jpeg,.png"
              :disabled="uploadLoading"
            >
              <el-button type="primary" :loading="uploadLoading">
                选择二维码图片
              </el-button>
            </el-upload>

            <div class="preview-img-group">
              <el-image
                v-for="(file, index) in wechatFileList"
                :key="index"
                :src="file.url"
                class="preview-img qr-img"
                fit="cover"
              />
            </div>
          </div>
          <template #tip>
            <div class="upload-tip">
              支持JPG/PNG格式，文件大小不超过1MB，建议尺寸200×200px
            </div>
          </template>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
          >
            保存设置
          </el-button>
          <el-button
            @click="handleReset"
            style="margin-left: 12px;"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.enterprise-params-page {
  /* 整个页面内边距20px，边框与页面边缘通过此内边距隔开 */
  padding: 20px;
  background-color: #f5f7fa; /* 页面背景色 */
  min-height: calc(100vh - 64px);
  box-sizing: border-box; /* 确保padding不影响整体尺寸 */

  /* 标题区域：带边框，独占一行 */
  .page-header {
    width: 100%; /* 独占一行 */
    background-color: #fff;
    border: 1px solid #e1e5eb; /* 标题边框 */
    border-radius: 6px;
    padding: 20px 25px; /* 标题内边距 */
    margin-bottom: 20px; /* 标题与表单间距 */
    box-sizing: border-box;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04); /* 轻微阴影 */

    .header-content {
      width: 100%;

      h2 {
        font-size: 18px;
        font-weight: 600;
        color: #1d2129;
        margin-bottom: 8px;
      }

      .sub-title {
        color: #666;
        font-size: 14px;
        line-height: 1.5;
      }
    }
  }

  /* 表单区域：带边框，独占一行 */
  .form-container {
    width: 100%; /* 独占一行 */
    background-color: #fff;
    border: 1px solid #e1e5eb; /* 表单边框 */
    border-radius: 6px;
    padding: 25px 30px; /* 表单内边距 */
    box-sizing: border-box;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04); /* 与标题阴影一致 */
  }

  .params-form {
    width: 100%;
  }

  /* 表单项间距 */
  .el-form-item {
    margin-bottom: 20px;
    align-items: center;

    &:last-child {
      margin-bottom: 0;
    }

    .el-form-item__label {
      font-size: 14px;
      color: #333;
    }
  }

  .upload-group {
    width: 20%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    flex-wrap: wrap;
  }

  .preview-img-group {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .preview-img {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    object-fit: cover;
    border: 1px solid #eee;
    transition: all 0.2s;

    &:hover {
      box-shadow: 0 0 0 2px #409eff;
    }
  }

  .upload-tip {
    color: #999;
    font-size: 12px;
    margin-top: 8px;
    line-height: 1.5;
    padding-left: 140px; /* 与label对齐 */
  }

  .form-help {
    color: #666;
    font-size: 12px;
    margin-top: 6px;
    line-height: 1.5;
  }

  /* 按钮区域 */
  .form-actions {
    margin-top: 30px;
    display: flex;
    justify-content: flex-start;
    padding-top: 15px;
    border-top: 1px dashed #e5e7eb;
  }

  /* 输入框样式优化 */
  .el-input__wrapper {
    border-radius: 4px;
    border-color: #e5e7eb;
    transition: border-color 0.2s;

    &:focus-within {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }
  }

  /* 按钮样式 */
  .el-button {
    border-radius: 4px;
  }
}
</style>
